<template>
  <el-drawer
    v-model="open"
    title="写评价"
    :with-header="true"
    size="80%"
    class="comment-drawer"
    :close-on-click-modal="false"
    :before-close="closeW"
    :append-to-body="true"
  >
    <el-form :inline="true" label-width="auto">
      <el-col :span="24">
        <el-form-item label="评分模版" prop="templateId">
          <el-select
            v-model="form.templateId"
            placeholder="请选择评分模版"
            clearable
            style="width: 240px"
            @change="handleChangeTemplate"
          >
            <el-option
              v-for="item in templateList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <div v-for="item in dimensionList" :key="item.id" style="display: flex">
        <span style="line-height: 40px">{{ item.name }}：</span>
        <el-rate
          v-model="item.score"
          size="large"
          show-score
          text-color="#ff9900"
          score-template="{value}分"
          clearable
        />
      </div>
      <el-col :span="24">
        <el-form-item label="" prop="desc">
          <el-input
            v-model="form.desc"
            type="textarea"
            placeholder="请输入评价内容"
            style="width: 542px"
          />
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <div
          v-for="(item, index) in fileList"
          :key="item.uid"
          class="item-wrap"
        >
          <div class="item-box">
            <el-image
              v-if="item.type === 2"
              class="rongqi"
              :src="item.src"
              :preview-src-list="[item.src]"
            >
            </el-image>
            <audio controls id="videoDiv" v-else-if="item.type === 1">
              <source :src="item.src" type="audio/ogg" />
            </audio>
            <video
              v-else-if="item.type === 3"
              class="rongqi"
              :src="item.src"
              controls
              :id="item.uid"
              @click="videoBtn(item.uid)"
            ></video>
          </div>
          <div class="control">
            <el-icon @click="delData(index)"><CloseBold /></el-icon>
            <el-icon @click="upData(index)" v-if="index !== 0"
              ><SortUp
            /></el-icon>
            <el-icon
              @click="downData(index)"
              v-if="index !== fileList.length - 1"
            >
              <SortDown />
            </el-icon>
          </div>
        </div>
      </el-col>
      <el-col :span="24">
        <div class="upload-content-page">
          <!-- <div class="itemBox mb16 textArea">
            <textarea rows="4" maxlength="1000" class="ant-input"></textarea>
            <div class="control"><div class="close"></div></div>
          </div> -->
          <el-alert
            type="warning"
            :closable="false"
            style="font-size: 14px; color: #666"
          >
            <template v-slot:title> 注意:至多可上传10个文件 </template>
          </el-alert>
          <div class="pannel" v-if="fileList.length < 10">
            <!-- <div class="item">
              <span class="iconfont icon-wenzi"></span>
              <div>文字</div>
            </div>
            <div class="item" @click="handleStart">
              <span class="iconfont icon-luyin"></span>
              <div>录音</div>
            </div> -->
            <el-upload
              :show-file-list="false"
              accept=".mp3,.m4a"
              class="item"
              :headers="upload.headers"
              action="#"
              :http-request="
                (event) => {
                  return uploadFiles(event, 1);
                }
              "
            >
              <div>
                <span class="iconfont icon-yinpin"></span>
                <div>音频</div>
              </div>
            </el-upload>
            <el-upload
              :show-file-list="false"
              accept=".jpg,.jpeg,.png"
              class="item"
              :headers="upload.headers"
              action="#"
              :http-request="
                (event) => {
                  return uploadFiles(event, 2);
                }
              "
            >
              <div>
                <span class="iconfont icon-tupian"></span>
                <div>图片</div>
              </div>
            </el-upload>
            <el-upload
              :show-file-list="false"
              accept=".mp4"
              class="item"
              action="#"
              :http-request="
                (event) => {
                  return uploadFiles(event, 3);
                }
              "
            >
              <div>
                <span class="iconfont icon-shipin"></span>
                <div>视频</div>
              </div>
            </el-upload>
            <!-- <el-upload
              :http-request="uploadFile"
              :show-file-list="false"
              action="#"
              accept=""
              class="item"
              :limit="1"
              :auto-upload="false"
            >
              <div class="item">
                <span class="iconfont icon-wenjian"></span>
                <div>文件</div>
              </div>
            </el-upload> -->
          </div>
        </div>
      </el-col>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeW">取消</el-button>
        <el-button
          type="primary"
          @click="handleSubmit()"
          :disabled="btnDisabled"
        >
          保存
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup>
import {
  getToken,
  getLoginDeptParentAuth,
  getLoginDeptAuth,
} from "@/utils/auth";
import { nextTick } from "vue";
import {
  getTemplateDetailAPI,
  uploadFileAPI,
  updateEvaluateAPI,
  getTemplateListAPI,
  deleteFileAPI,
} from "@/api/interaction/comment";
const emits = defineEmits(["refreshPage"]);
const { proxy } = getCurrentInstance();
const loading = ref(false);
const open = ref(false);
const courseId = ref(null);
const templateList = ref([]);

const currentItemList = ref({});

const btnDisabled = ref(false);

const data = reactive({
  form: {
    templateId: null,
    desc: null,
  },
  fileList: [],
  upload: {
    headers: {
      Authorization: "Bearer " + getToken(),
      LoginDeptParentAuth: getLoginDeptParentAuth(),
      LoginDeptAuth: getLoginDeptAuth(),
    },
    // 上传的地址
    url: import.meta.env.VITE_APP_BASE_API + "/tClass/importList",
  },
});

const { form, fileList, upload } = toRefs(data);

const dimensionList = ref([]);

// 处理方法---------------------------------------------------------------------------------------------------------
// function getBase64ImagePrefix(fileExtension) {
//   //const mimeType = getImageMimeType(fileExtension);
//   return "data:image/" + fileExtension + ";base64,";
// }
// function getImageMimeType(fileExtension) {
//   switch (fileExtension) {
//     case "jpg":
//     case "jpeg":
//       return "image/jpeg";
//     case "png":
//       return "image/png";
//     case "gif":
//       return "image/gif";
//     case "bmp":
//       return "image/bmp";
//     case "webp":
//       return "image/webp";
//     default:
//       return "image/" + fileExtension; // 对于不常见的格式，可能需要增加更多情况，或者返回默认值
//   }
// }

function videoBtn(uid) {
  const video = document.getElementById(uid);
  video.webkitRequestFullScreen();
}

// 事件------------------------------------------------------------------------------------------------------------
function openW(itemList, cId) {
  resetData();
  courseId.value = cId;
  currentItemList.value = itemList;
  open.value = true;
  nextTick(() => {
    initPage();
  });
}

function closeW() {
  open.value = false;
}

function resetData() {
  fileList.value = [];
  dimensionList.value = [];
  form.value = {
    templateId: null,
    desc: null,
  };
}

function upData(index) {
  let temp = fileList.value[index];
  fileList.value[index] = fileList.value[index - 1];
  fileList.value[index - 1] = temp;
}

function downData(index) {
  let temp = fileList.value[index];
  fileList.value[index] = fileList.value[index + 1];
  fileList.value[index + 1] = temp;
}

async function delData(index) {
  await deleteFileAPI([fileList.value[index].src]);
  fileList.value = fileList.value.filter((data, i) => {
    return i !== index;
  });
}

function handleChangeTemplate(id) {
  if (id) {
    loading.value = true;
    getTemplateDetailAPI({ id })
      .then((response) => {
        loading.value = false;
        let arr = response.data[0].tName;
        arr.forEach((item) => {
          item.score = 0;
          item.lId = item.id;
        });
        dimensionList.value = arr;
      })
      .catch(() => {
        loading.value = false;
      });
  } else {
    dimensionList.value = [];
  }
}

function playAudio() {
  var myAudio = document.getElementById("myAudio");
  myAudio.play();
}

function pauseAudio() {
  var myAudio = document.getElementById("myAudio");
  myAudio.pause();
}

function refreshParent() {
  emits("refreshPage");
}
// 方法----------------------------------------------------------------------------------------------------------------------------

function getTemplateList() {
  loading.value = true;
  getTemplateListAPI({ pageSize: 9999, pageNum: 1, state: 1 }).then(
    (response) => {
      let list = response.rows;
      let newList = [];
      list.forEach((element) => {
        let courseIdArr = element.courseId.split(",");
        if (courseIdArr.includes(courseId.value)) {
          element.default = true;
          form.value.templateId = element.id;
          handleChangeTemplate(element.id);
        } else {
          element.default = false;
        }
        if (element.state === 1) {
          newList.push(element);
        }
      });
      templateList.value = list;
      loading.value = false;
    }
  );
}

function uploadFiles(event, type) {
  const { uid } = event;
  let formData = new FormData();
  formData.append("file", event.file);
  uploadFileAPI(formData).then((res) => {
    if (res.code === 200) {
      fileList.value.push({
        id: uid,
        src: res.data[0],
        type,
      });
    }
  });
}

function saveComment(map) {
  loading.value = true;
  updateEvaluateAPI(map).then((response) => {
    proxy.$modal.msgSuccess("评价保存成功");
    closeW();
    refreshParent();
    loading.value = false;
    btnDisabled.value = false;
  });
}

function handleSubmit() {
  if (!form.value.desc) {
    proxy.$modal.msgError("请输入评价内容");
    return;
  }
  let urlArr = [];
  fileList.value.forEach((file) => {
    urlArr.push(file.src);
  });

  // btnDisabled.value = true;
  // proxy.$refs["rulesRef"].validate((valid) => {
  //   if (valid) {
  let map = {};
  map.state = "0";
  map.ids = currentItemList.value;
  map.description = form.value.desc;
  map.tEvaluateScores = dimensionList.value;
  map.url = urlArr;
  saveComment(map);
  //   } else {
  //     proxy.$modal.msgError("表单校验未通过，请重新检查提交内容");
  //     btnDisabled.value = false;
  //   }
  // });
}

function initPage() {
  getTemplateList();
}

defineExpose({ openW }); // 用于父组件调用
</script>

<style lang="scss" scoped>
.upload-content-page {
  width: 542px;
  .itemBox {
    position: relative;
    border: 1px solid #e8e8e8;
    border-radius: 4px;
    padding: 16px;
    margin-bottom: 16px !important;
  }
  .pannel {
    padding: 16px 0;
    display: flex;
    justify-content: center;
    text-align: center;
    font-size: 14px;
    line-height: 20px;
    background: #fff;
    border-radius: 4px;
    border: 1px dashed #e8e8e8;
    margin-bottom: 16px;
    .item {
      cursor: pointer;
      width: 30px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      flex: 1;
      span {
        color: #999;
        font-size: 23px;
        line-height: 23px;
        width: 24px;
        height: 24px;
      }
      span:hover {
        color: #409eff;
      }
      div {
        word-break: break-word;
      }
    }
  }
  .require-content-extra {
    font-size: 14px;
    color: #999;
    line-height: 20px;
  }

  .textArea {
    border: 0;
    padding: 0;
  }
  textarea.ant-input {
    width: 100%;
    height: auto;
    min-height: 32px;
    line-height: 1.5;
    vertical-align: bottom;
    -webkit-transition: all 0.3s, height 0s;
    transition: all 0.3s, height 0s;
    color: rgba(0, 0, 0, 0.65);
    border-color: #e8e8e8;
    outline-color: #409eff;
  }
  // .control {
  //   position: absolute;
  //   top: 4px;
  //   right: -20px;
  //   width: 20px;

  //   .close {
  //     width: 20px;
  //     height: 20px;
  //     cursor: pointer;
  //     margin-bottom: 4px;
  //     background: url(https://image.xiaomaiketang.com/xm/eesMPhNP3e.png)
  //       no-repeat 100% 100%;
  //     background-size: 100% 100%;
  //   }
  // }
}
.item-wrap {
  position: relative;
  width: 96.5%;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  padding: 16px;
  margin-bottom: 16px;
  .item-box {
    display: flex;

    .rongqi {
      object-fit: cover;
      position: relative;
      min-width: 180px;
      height: 180px;
      margin-right: 12px;
      border-radius: 4px;
      box-sizing: border-box;
    }
    // .xm-audio {
    //   display: flex;
    //   align-items: center;
    //   width: 360px;
    //   height: 60px;
    //   box-shadow: 0 2px 6px 0 rgba(0, 0, 0, 0.1);
    //   border-radius: 4px;
    //   padding: 8px !important;
    //   background-color: #fff;
    //   .audio-cover {
    //     width: 44px;
    //     height: 44px;
    //   }
    //   .progress-bar {
    //     width: 240px;
    //     height: 50px;
    //     margin-left: 8px;
    //     display: flex;
    //     flex-direction: column;
    //     justify-content: space-around;
    //   }
    //   .audio_image {
    //     width: 28px !important;
    //     height: 28px;
    //     position: relative;
    //     right: -10px;
    //   }
    // }
  }

  .control {
    position: absolute;
    top: 4px;
    right: -20px;
    width: 20px;
  }
}
</style>
